<template>
  <el-drawer title="导入文件" :visible.sync="innerValue" direction="rtl" append-to-body @open="onDrawerOpen">
    <div class="p-[20px]">
      <div>
        <!--
          <div class="flex justify-between">
          <div v-for="(item, index) in stepTitle" class="relative flex flex-1 flex-col items-center" :key="index">
          <div :class="[currentStep == item.value ? 'active' : '', 'default']">{{ item.value }}</div>
          <div class="pt-[4px] text-black">{{ item.label }}</div>
          <div class="steps-line-left" v-if="item.value == 2 || item.value == 3"></div>
          <div class="steps-line-right" v-if="item.value == 1 || item.value == 2"></div>
          </div>
          </div>
        -->
        <el-steps :active="currentStep" align-center>
          <el-step v-for="(item, index) in stepTitle" :key="index" :title="item.label"></el-step>
        </el-steps>
      </div>
      <div v-if="currentStep == 1" class="relative">
        <div class="pl-[52px] pt-[20px]">
          <div>填写信息</div>
          <div class="pb-[12px] pt-[4px]">请按照数据模板的格式准备导入数据,单次导入的数据不超过10000条</div>
          <t-button type="primary" class="common-search-btn" @click="downloadTemplate">下载模板</t-button>
        </div>
        <div class="pl-[52px]">
          <div class="pt-[20px]">上传信息文件</div>
          <div class="pb-[12px] pt-[4px]">文件为EXcel格式,文件大小不要超过200M</div>
          <el-upload
            ref="upload"
            action="#"
            class="avatar-uploader"
            :file-list="fileList"
            :auto-upload="false"
            :on-change="onChange"
            :on-remove="handleRemove"
            :http-request="uploadFiles"
            multiple
          >
            <t-button slot="trigger" className="uploadClass" svgIcon="ic-upload">点击上传</t-button>
          </el-upload>
        </div>
        <t-button type="primary" class="common-search-btn absolute left-2/4 -translate-x-2/4" @click="submitUpload"
          >下一步</t-button
        >
      </div>
      <div v-if="currentStep == 2" class="px-[20px]">
        <el-progress :percentage="percentage" status="success"></el-progress>
        <div class="pb-[10px] text-center">导入进度 {{ percentage }}%</div>
        <div class="flex justify-center">
          <t-button class="common-search-btn" type="primary" :disabled="!percentage == 100" @click="currentStep = 3"
            >下一步</t-button
          >
          <t-button
            class="common-search-btn"
            type="primary"
            :disabled="!(percentage == 100 || percentageType != 'init')"
            @click="reUpload"
            >重新上传</t-button
          >
        </div>
      </div>
      <div v-if="currentStep == 3">
        <div class="mt-[10px] text-center">导入成功</div>
        <div class="text-center">本次成功导入了{{ totalDatas }}条数据信息!!!</div>
        <div class="mt-[10px] flex justify-center">
          <t-button class="common-search-btn" type="primary" @click="onSubmit">完 成</t-button>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import vModelMixin from "@/mixin/v-model";
import exportBlob from "@/util/exportBlob";
import { systemDeleteFile, systemUploadFile } from "@/api/file";
export default {
  name: "FileUpload",
  mixins: [vModelMixin],
  props: {
    bizType: {
      type: String,
      required: true,
    },
    ext: {
      type: Array,
      default: () => ["xls", "xlsx"],
    },
  },
  data() {
    return {
      percentageType: "init", //init 初始  success 成功 error 失败  初始状态不允许重新上传
      currentStep: 1,
      stepTitle: [
        { label: "上传文件", value: 1 },
        { label: "执行导入", value: 2 },
        { label: "导入完成", value: 3 },
      ],
      fileList: [],
      totalDatas: 0,
      percentage: 0,
    };
  },
  methods: {
    onDrawerOpen() {
      this.currentStep = 1;
      this.percentageType = "init";
    },
    downloadTemplate() {
      const options = {
        url: "",
      };
      exportBlob(options);
    },
    onChange(file, list) {
      console.log(list.length);
      if (file.status !== "ready") return;
      const suffName = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = this.ext.indexOf(suffName) >= 0;
      const isLt200M = file.size / 1024 / 1024 < 200;
      if (!extension) {
        this.$message({
          message: `上传文件只支持 ${this.ext.join(" / ")} 格式！`,
          type: "warning",
        });
        list.splice(list.length == 2 ? 1 : 0, 1);
        return false;
      }
      if (!isLt200M) {
        this.$message({
          message: "上传文件大小不能超过 200MB!",
          type: "warning",
        });
        list.splice(list.length == 2 ? 1 : 0, 1);
        return false;
      }
      if (list.length > 1 && file.status !== "fail") {
        list.splice(0, 1);
      } else if (file.status === "fail") {
        this.$message("上传失败，请重新上传！");
        list.splice(0, 1);
      }
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter((item) => item.uid !== file.uid);
      this.$message.success({
        message: "删除成功",
      });
    },
    async submitUpload() {
      this.$refs.upload.submit();
      console.log(this.fileList);
      if (this.fileList.length) {
        this.currentStep = 2;
        this.percentageType = "init";
        try {
          const { id } = await systemUploadFile(
            {
              file: this.fileList[0],
              bizType: this.bizType,
            },
            {
              onUploadProgress: (progress) => {
                console.log(progress);
                const rate = Math.floor((progress.loaded / progress.total) * 100);
                if (rate < 100) {
                  this.percentage = rate;
                }
              },
            },
          );
          this.fileList[0].id = id;
          this.percentage = 100;
          this.percentageType = "success";
          this.totalDatas = id;
        } catch (error) {
          this.percentage = 0;
          this.percentageType = "error";
          this.$message.error(error);
        }
      } else {
        this.$message.error(`请选择文件`);
      }
    },
    uploadFiles(raw) {
      this.fileList.push(raw.file);
    },
    async reUpload() {
      if (this.percentageType == "success") {
        await systemDeleteFile({ id: this.fileList[0].id });
      }
      this.fileList = [];
      this.currentStep = 1;
    },
    onSubmit() {
      this.innerValue = false;
      this.fileList = [];
      this.$emit("on-submit");
    },
  },
};
</script>

<style lang="scss" scoped>
.upload_wrap {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: none;
}

::v-deep .el-list-enter,
::v-deep .el-list-leave-active {
  opacity: 0;
}

::v-deep .el-upload-list__item-name {
  width: 300px;
}

::v-deep .el-upload-list {
  height: 40px;
}

// .steps-line-left,
// .steps-line-right {
//   position: absolute;
//   top: 15px;
//   width: calc(50% - 15px);
//   height: 1px;
//   background: #d0d0d0;
// }

// .steps-line-left {
//   left: 0;
// }

// .steps-line-right {
//   right: 0;
// }

// .default {
//   width: 30px;
//   height: 30px;
//   line-height: 30px;
//   text-align: center;
//   border: 1px solid #2494fa;
//   border-radius: 50%;
// }

// .active {
//   background: #2494fa;
// }
</style>
